<template>
  <div class="container" style="margin-bottom: 5vh">
    <!-- 汇总表格部分 -->
    <div class="summary-section">
      <div class="header" >
        <h2 class="title" style="margin-top: 15px">汇总表格</h2>
        <p class="subtitle" style="margin-top: 18px">为您轻松统计汇总您的学术成果</p>
      </div>
      <hr class="divider">

      <div class="table-container">
        <table class="summary-table">
          <thead>
          <tr>
            <th>类别</th>
            <th v-for="(header, index) in headers" :key="index" @click="updateSelectedType(header)" style="cursor: pointer;">
              {{ header }}
            </th>
          </tr>
          </thead>
          <tbody>
          <tr>
            <td>数量</td>
            <td style="cursor: pointer" v-for="(count, index) in counts" :key="index"
                :class="{ 'highlight': count > 0 }"
                @click="updateSelectedType(headers[index])">
              {{ count }}
            </td>
          </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 分类汇总部分 -->
    <div class="detail-section" >
      <h3 class="section-title">分类汇总</h3>

      <div class="filters">
        <div class="select-wrapper">
          <select v-model="selectedType" disabled>
            <option value="" disabled>选择材料类型</option>
            <option v-for="header in headers" :key="header" :value="header">{{ header }}</option>
          </select>
          <span class="select-arrow"></span>
        </div>

        <!-- 替换原来的时间选择下拉框为日期范围选择器 -->

        <div class="select-wrapper">
          <select v-model="selectedPerson">
            <option value="" disabled selected>选择本人排名</option>
            <option v-for="rank in rankings" :key="rank">{{ rank }}</option>
          </select>
          <span class="select-arrow"></span>
        </div>

        <div class="date-range-picker">
          <span class="date-label">时间范围：</span>
          <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleDateRangeChange"
          />
        </div>
        <button class="export-btn" @click="exportToExcel" :disabled="!selectedType">导出到Excel</button>
        <button class="export-btn word-btn" @click="exportToWord" :disabled="!selectedType">导出到Word</button>
      </div>

      <div class="table-container" >
        <table class="detail-table" style="margin-bottom: 3vh">
          <thead>
          <tr>
            <th>序号</th>
            <template v-if="selectedType === '论文'">
              <th v-for="(header, index) in getVisibleHeaders('论文')" :key="index" class="header-cell">
                {{ header }}
                <button
                    @click.stop="deleteColumn('论文', index)"
                    class="delete-btn"
                    title="删除列"
                >
                  <XIcon class="delete-icon" />
                </button>
              </th>
            </template>
            <template v-else-if="selectedType === '专利'">
              <th v-for="(header, index) in getVisibleHeaders('专利')" :key="index" class="header-cell">
                {{ header }}
                <button
                    @click.stop="deleteColumn('专利', index)"
                    class="delete-btn"
                    title="删除列"
                >
                  <XIcon class="delete-icon" />
                </button>
              </th>
            </template>
            <template v-else-if="selectedType === '软件著作权'">
              <th v-for="(header, index) in getVisibleHeaders('软件著作权')" :key="index" class="header-cell">
                {{ header }}
                <button
                    @click.stop="deleteColumn('软件著作权', index)"
                    class="delete-btn"
                    title="删除列"
                >
                  <XIcon class="delete-icon" />
                </button>
              </th>
            </template>
            <template v-else-if="selectedType === '个人获奖'">
              <th v-for="(header, index) in getVisibleHeaders('个人获奖')" :key="index" class="header-cell">
                {{ header }}
                <button
                    @click.stop="deleteColumn('个人获奖', index)"
                    class="delete-btn"
                    title="删除列"
                >
                  <XIcon class="delete-icon" />
                </button>
              </th>
            </template>
            <template v-else-if="selectedType === '学生获奖'">
              <th v-for="(header, index) in getVisibleHeaders('学生获奖')" :key="index" class="header-cell">
                {{ header }}
                <button
                    @click.stop="deleteColumn('学生获奖', index)"
                    class="delete-btn"
                    title="删除列"
                >
                  <XIcon class="delete-icon" />
                </button>
              </th>
            </template>
            <template v-else-if="selectedType === '继续教育材料'">
              <th v-for="(header, index) in getVisibleHeaders('继续教育材料')" :key="index" class="header-cell">
                {{ header }}
                <button
                    @click.stop="deleteColumn('继续教育材料', index)"
                    class="delete-btn"
                    title="删除列"
                >
                  <XIcon class="delete-icon" />
                </button>
              </th>
            </template>
            <template v-else-if="selectedType === '著作'">
              <th v-for="(header, index) in getVisibleHeaders('著作')" :key="index" class="header-cell">
                {{ header }}
                <button
                    @click.stop="deleteColumn('著作', index)"
                    class="delete-btn"
                    title="删除列"
                >
                  <XIcon class="delete-icon" />
                </button>
              </th>
            </template>
            <template v-else-if="selectedType === '新闻报道'">
              <th v-for="(header, index) in getVisibleHeaders('新闻报道')" :key="index" class="header-cell">
                {{ header }}
                <button
                    @click.stop="deleteColumn('新闻报道', index)"
                    class="delete-btn"
                    title="删除列"
                >
                  <XIcon class="delete-icon" />
                </button>
              </th>
            </template>
            <template v-else-if="selectedType === '档案资料'">
              <th v-for="(header, index) in getVisibleHeaders('档案资料')" :key="index" class="header-cell">
                {{ header }}
                <button
                    @click.stop="deleteColumn('档案资料', index)"
                    class="delete-btn"
                    title="删除列"
                >
                  <XIcon class="delete-icon" />
                </button>
              </th>
            </template>
            <template v-else-if="selectedType === '其他'">
              <th v-for="(header, index) in getVisibleHeaders('其他')" :key="index" class="header-cell">
                {{ header }}
                <button
                    @click.stop="deleteColumn('其他', index)"
                    class="delete-btn"
                    title="删除列"
                >
                  <XIcon class="delete-icon" />
                </button>
              </th>
            </template>
            <template v-else-if="selectedType === '横向课题'">
              <th v-for="(header, index) in getVisibleHeaders('横向课题')" :key="index" class="header-cell">
                {{ header }}
                <button
                    @click.stop="deleteColumn('横向课题', index)"
                    class="delete-btn"
                    title="删除列"
                >
                  <XIcon class="delete-icon" />
                </button>
              </th>
            </template>
            <template v-else-if="selectedType === '纵向课题'">
              <th v-for="(header, index) in getVisibleHeaders('纵向课题')" :key="index" class="header-cell">
                {{ header }}
                <button
                    @click.stop="deleteColumn('纵向课题', index)"
                    class="delete-btn"
                    title="删除列"
                >
                  <XIcon class="delete-icon" />
                </button>
              </th>
            </template>
          </tr>
          </thead>
          <tbody>
          <template v-if="selectedType === '论文'">
            <tr v-for="(paper, index) in filteredData" :key="index">
              <td class="row-header">{{ index + 1 }}</td>
              <td v-for="header in getVisibleHeaders('论文')" :key="header">
                {{ formatCellValue(paper[getPropertyName('论文', header)], header) }}
              </td>
              <td>
                <button
                    @click="deleteRow(index)"
                    class="delete-row-btn"
                    title="删除行"
                >
                  <TrashIcon class="delete-icon" />
                </button>
              </td>
            </tr>
          </template>
          <template v-else-if="selectedType === '专利'">
            <tr v-for="(patent, index) in filteredData" :key="index">
              <td class="row-header">{{ index + 1 }}</td>
              <td v-for="header in getVisibleHeaders('专利')" :key="header">
                {{ formatCellValue(patent[getPropertyName('专利', header)], header) }}
              </td>
              <td>
                <button
                    @click="deleteRow(index)"
                    class="delete-row-btn"
                    title="删除行"
                >
                  <TrashIcon class="delete-icon" />
                </button>
              </td>
            </tr>
          </template>
          <template v-else-if="selectedType === '软件著作权'">
            <tr v-for="(copyright, index) in filteredData" :key="index">
              <td class="row-header">{{ index + 1 }}</td>
              <td v-for="header in getVisibleHeaders('软件著作权')" :key="header">
                {{ formatCellValue(copyright[getPropertyName('软件著作权', header)], header) }}
              </td>
              <td>
                <button
                    @click="deleteRow(index)"
                    class="delete-row-btn"
                    title="删除行"
                >
                  <TrashIcon class="delete-icon" />
                </button>
              </td>
            </tr>
          </template>
          <template v-else-if="selectedType === '个人获奖'">
            <tr v-for="(award, index) in filteredData" :key="index">
              <td class="row-header">{{ index + 1 }}</td>
              <td v-for="header in getVisibleHeaders('个人获奖')" :key="header">
                {{ formatCellValue(award[getPropertyName('个人获奖', header)], header) }}
              </td>
              <td>
                <button
                    @click="deleteRow(index)"
                    class="delete-row-btn"
                    title="删除行"
                >
                  <TrashIcon class="delete-icon" />
                </button>
              </td>
            </tr>
          </template>
          <template v-else-if="selectedType === '学生获奖'">
            <tr v-for="(award, index) in filteredData" :key="index">
              <td class="row-header">{{ index + 1 }}</td>
              <td v-for="header in getVisibleHeaders('学生获奖')" :key="header">
                {{ formatCellValue(award[getPropertyName('学生获奖', header)], header) }}
              </td>
              <td>
                <button
                    @click="deleteRow(index)"
                    class="delete-row-btn"
                    title="删除行"
                >
                  <TrashIcon class="delete-icon" />
                </button>
              </td>
            </tr>
          </template>
          <template v-else-if="selectedType === '继续教育材料'">
            <tr v-for="(material, index) in filteredData" :key="index">
              <td class="row-header">{{ index + 1 }}</td>
              <td v-for="header in getVisibleHeaders('继续教育材料')" :key="header">
                {{ formatCellValue(material[getPropertyName('继续教育材料', header)], header) }}
              </td>
              <td>
                <button
                    @click="deleteRow(index)"
                    class="delete-row-btn"
                    title="删除行"
                >
                  <TrashIcon class="delete-icon" />
                </button>
              </td>
            </tr>
          </template>
          <template v-else-if="selectedType === '著作'">
            <tr v-for="(publication, index) in filteredData" :key="index">
              <td class="row-header">{{ index + 1 }}</td>
              <td v-for="header in getVisibleHeaders('著作')" :key="header">
                {{ formatCellValue(publication[getPropertyName('著作', header)], header) }}
              </td>
              <td>
                <button
                    @click="deleteRow(index)"
                    class="delete-row-btn"
                    title="删除行"
                >
                  <TrashIcon class="delete-icon" />
                </button>
              </td>
            </tr>
          </template>
          <template v-else-if="selectedType === '新闻报道'">
            <tr v-for="(report, index) in filteredData" :key="index">
              <td class="row-header">{{ index + 1 }}</td>
              <td v-for="header in getVisibleHeaders('新闻报道')" :key="header">
                {{ formatCellValue(report[getPropertyName('新闻报道', header)], header) }}
              </td>
              <td>
                <button
                    @click="deleteRow(index)"
                    class="delete-row-btn"
                    title="删除行"
                >
                  <TrashIcon class="delete-icon" />
                </button>
              </td>
            </tr>
          </template>
          <template v-else-if="selectedType === '档案资料'">
            <tr v-for="(certification, index) in filteredData" :key="index">
              <td class="row-header">{{ index + 1 }}</td>
              <td v-for="header in getVisibleHeaders('档案资料')" :key="header">
                {{ formatCellValue(certification[getPropertyName('档案资料', header)], header) }}
              </td>
              <td>
                <button
                    @click="deleteRow(index)"
                    class="delete-row-btn"
                    title="删除行"
                >
                  <TrashIcon class="delete-icon" />
                </button>
              </td>
            </tr>
          </template>
          <template v-else-if="selectedType === '其他'">
            <tr v-for="(other, index) in filteredData" :key="index">
              <td class="row-header">{{ index + 1 }}</td>
              <td v-for="header in getVisibleHeaders('其他')" :key="header">
                {{ formatCellValue(other[getPropertyName('其他', header)], header) }}
              </td>
              <td>
                <button
                    @click="deleteRow(index)"
                    class="delete-row-btn"
                    title="删除行"
                >
                  <TrashIcon class="delete-icon" />
                </button>
              </td>
            </tr>
          </template>
          <template v-else-if="selectedType === '横向课题'">
            <tr v-for="(horizontal, index) in filteredData" :key="index">
              <td class="row-header">{{ index + 1 }}</td>
              <td v-for="header in getVisibleHeaders('横向课题')" :key="header">
                {{ formatCellValue(horizontal[getPropertyName('横向课题', header)], header) }}
              </td>
              <td>
                <button
                    @click="deleteRow(index)"
                    class="delete-row-btn"
                    title="删除行"
                >
                  <TrashIcon class="delete-icon" />
                </button>
              </td>
            </tr>
          </template>
          <template v-else-if="selectedType === '纵向课题'">
            <tr v-for="(longitudinal, index) in filteredData" :key="index">
              <td class="row-header">{{ index + 1 }}</td>
              <td v-for="header in getVisibleHeaders('纵向课题')" :key="header">
                {{ formatCellValue(longitudinal[getPropertyName('纵向课题', header)], header) }}
              </td>
              <td>
                <button
                    @click="deleteRow(index)"
                    class="delete-row-btn"
                    title="删除行"
                >
                  <TrashIcon class="delete-icon" />
                </button>
              </td>
            </tr>
          </template>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import * as XLSX from 'xlsx'
import { XIcon, TrashIcon } from 'lucide-vue-next'
import { Document, Paragraph, Table, TableRow, TableCell, WidthType, BorderStyle, Packer } from 'docx'
import { saveAs } from 'file-saver'
import { ElMessageBox, ElMessage, ElDatePicker } from 'element-plus' // 确保引入ElDatePicker

// API导入
import {
  getUserPersonalCount,
  getPatentsBySummary,
  getCopyRightsBySummary,
  getPersonalAwardsBySummary,
  getStudentAwardsBySummary,
  getcemBySummary,
  getcemPublicationSummary,
  getreportBySummary,
  getcertificationBySummary,
  getotherBySummary,
  gethorizontalBySummary,
  getlongitudinalBySummary,
  getpapersBySummary
} from "@/api/Assistants/SummaryTable.js"

// 状态管理
const selectedPeriod = ref('all')
const selectedType = ref('')
// 替换selectedTime为日期范围
const dateRange = ref([])
const selectedPerson = ref('')

// 数据存储
const patentData = ref([])
const copyrightData = ref([])
const personalAwardData = ref([])
const studentAwardData = ref([])
const cemData = ref([])
const publicationData = ref([])
const reportData = ref([])
const certificationData = ref([])
const otherData = ref([])
const horizontalData = ref([])
const longitudinalData = ref([])
const papersData = ref([])

const headers = [
  '论文', '纵向课题', '专利', '软件著作权', '个人获奖',
  '学生获奖', '继续教育材料', '著作', '横向课题',
  '新闻报道', '档案资料', '其他'
]

const counts = ref([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])

// 移除原来的timeOptions
// const timeOptions = ['2025年','2024年','2023年', '2022年', '2021年','2020年', '2019年', '2018年']
const rankings = ["前1名","前2名","前3名","第一名","第二名","第三名","第四名","第五名","全部排名"]

// 表头配置
const defaultHeaders = {
  '论文': [
    '论文题目', '论文类型', '研究领域', '本人排名', '通讯作者',
    '期刊名称', '收录情况', '发表日期', 'DOI', '被引次数',
    '关键词', '页码范围', '影响因子', '卷号', '期号',
    'ISSN', 'CN号'
  ],
  '专利': [
    '专利名称', '专利类型', '专利编号', '授权公告日', '专利申请日',
    '本人排名', '申请编号', '专利状态', '专利权人'
  ],
  '软件著作权': [
    '著作权名称', '证书号', '获得时间', '著作权类型', '著作权人',
    '本人排名', '开发完成时间', '登记号'
  ],
  '个人获奖': [
    '荣誉名称', '获奖名次', '级别', '授予单位', '获奖时间', '本人排名'
  ],
  '学生获奖': [
    '比赛名称', '获奖名次', '级别', '授予单位', '获奖时间', '本人排名', '获奖学生'
  ],
  '继续教育材料': [
    '材料标题', '课时', '评分/等级', '获得时间', '培训单位'
  ],
  '著作': [
    '著作名称', '本人排名', '角色', '出版社', '类型', '出版日期',
    'ISBN', '出版地', '字数（万字）'
  ],
  '新闻报道': [
    '报道标题', '媒体级别', '报道时间', '栏目/版面', '在线链接', '媒体名称'
  ],
  '档案资料': [
    '证书标题', '获得时间', '证书类型', '证书编号', '授予机构'
  ],
  '其他': [
    '成果名称', '本人排名', '获得时间'
  ],
  '横向课题': [
    '课题名称', '合同来源', '合同编号', '到账经费(万)', '课题状态',
    '开始时间', '本人排名', '截止时间'
  ],
  '纵向课题': [
    '课题名称', '基金名称', '课题类型', '授予单位', '课题级别',
    '课题编号', '到账经费(万)', '本人排名', '开始时间', '截止时间', '课题状态'
  ]
}

// 可见列管理
const visibleHeaders = ref({...defaultHeaders})

// 获取可见表头
const getVisibleHeaders = (type) => {
  return visibleHeaders.value[type] || []
}

// 删除列
const deleteColumn = (type, index) => {
  if (visibleHeaders.value[type].length > 1) {
    visibleHeaders.value[type] = visibleHeaders.value[type].filter((_, i) => i !== index)
  }
}

// 属性名映射
const propertyMap = {
  '论文': {
    '论文题目': 'title',
    '论文类型': 'paperType',
    '研究领域': 'researchField',
    '本人排名': 'authorRank',
    '通讯作者': 'correspondingAuthor',
    '期刊名称': 'journalName',
    '收录情况': 'indexing',
    '发表日期': 'publishDate',
    'DOI': 'doi',
    '被引次数': 'citationCount',
    '关键词': 'keywords',
    '页码范围': 'pageRange',
    '影响因子': 'impactFactor',
    '卷号': 'volumeNumber',
    '期号': 'issueNumber',
    'ISSN': 'issn',
    'CN号': 'cnNumber'
  },
  '专利': {
    '专利名称': 'title',
    '专利类型': 'patentType',
    '专利编号': 'patentNumber',
    '授权公告日': 'authorizationDate',
    '专利申请日': 'applicationDate',
    '本人排名': 'authorRank',
    '申请编号': 'applicationNumber',
    '专利状态': 'patentStatus',
    '专利权人': 'patentOwner'
  },
  '软件著作权': {
    '著作权名称': 'title',
    '证书号': 'certificateNo',
    '获得时间': 'puttime',
    '著作权类型': 'copyrightType',
    '著作权人': 'copyrightOwner',
    '本人排名': 'authorRank',
    '开发完成时间': 'finishTime',
    '登记号': 'registerNo'
  },
  '个人获奖': {
    '荣誉名称': 'title',
    '获奖名次': 'awardLevel',
    '级别': 'level',
    '授予单位': 'grantingUnit',
    '获奖时间': 'awardTime',
    '本人排名': 'authorRank'
  },
  '学生获奖': {
    '比赛名称': 'title',
    '获奖名次': 'awardLevel',
    '级别': 'level',
    '授予单位': 'grantingUnit',
    '获奖时间': 'awardTime',
    '本人排名': 'authorRank',
    '获奖学生': 'awardStudents'
  },
  '继续教育材料': {
    '材料标题': 'title',
    '课时': 'hours',
    '评分/等级': 'score',
    '获得时间': 'obtainTime',
    '培训单位': 'trainingUnit'
  },
  '著作': {
    '著作名称': 'title',
    '本人排名': 'authorRank',
    '角色': 'role',
    '出版社': 'publisher',
    '类型': 'type',
    '出版日期': 'publishDate',
    'ISBN': 'isbn',
    '出版地': 'location',
    '字数（万字）': 'wordCount'
  },
  '新闻报道': {
    '报道标题': 'title',
    '媒体级别': 'mediaLevel',
    '报道时间': 'reportTime',
    '栏目/版面': 'columnSection',
    '在线链接': 'onlineLink',
    '媒体名称': 'mediaName'
  },
  '档案资料': {
    '证书标题': 'title',
    '获得时间': 'obtainTime',
    '证书类型': 'certificateType',
    '证书编号': 'certificateNumber',
    '授予机构': 'issuingInstitution'
  },
  '其他': {
    '成果名称': 'title',
    '本人排名': 'authorRank',
    '获得时间': 'obtainTime'
  },
  '横向课题': {
    '课题名称': 'projectName',
    '合同来源': 'contractSource',
    '合同编号': 'contractNumber',
    '到账经费(万)': 'fundingAmount',
    '课题状态': 'projectStatus',
    '开始时间': 'startTime',
    '本人排名': 'rank',
    '截止时间': 'endTime'
  },
  '纵向课题': {
    '课题名称': 'projectName',
    '基金名称': 'fundName',
    '课题类型': 'projectType',
    '授予单位': 'grantingUnit',
    '课题级别': 'projectLevel',
    '课题编号': 'projectNumber',
    '到账经费(万)': 'fundingAmount',
    '本人排名': 'rank',
    '开始时间': 'startTime',
    '截止时间': 'endTime',
    '课题状态': 'projectStatus'
  }
}

// 获取属性名
const getPropertyName = (type, header) => {
  return propertyMap[type]?.[header] || header
}

// 格式化单元格值
const formatCellValue = (value, header) => {
  if (value === null || value === undefined) return '-'

  // 处理个人排名
  if (header === '本人排名') {
    return value || '-'
  }

  // 处理日期
  if (header.includes('日期') || header.includes('时间')) {
    return formatDate(value)
  }

  // 处理布尔值
  if (typeof value === 'boolean') {
    return value ? '是' : '否'
  }

  return value
}

// 处理日期范围变化
const handleDateRangeChange = (val) => {
  if (val && val.length === 2) {
    // 可以在这里根据日期范围重新获取数据
    console.log('日期范围变化:', val)
    // 如果需要，可以在这里调用API重新获取数据
    if (selectedType.value) {
      updateSelectedType(selectedType.value)
    }
  }
}

// 过滤后的数据
const filteredData = computed(() => {
  let currentData = getCurrentData()

  // 如果有日期范围，进行过滤
  if (dateRange.value && dateRange.value.length === 2) {
    const startDate = new Date(dateRange.value[0])
    const endDate = new Date(dateRange.value[1])

    // 根据不同类型选择对应的日期字段进行过滤
    let dateField = 'publishDate' // 默认使用发表日期

    switch (selectedType.value) {
      case '论文': dateField = 'publishDate'; break;
      case '专利': dateField = 'authorizationDate'; break;
      case '软件著作权': dateField = 'puttime'; break;
      case '个人获奖': dateField = 'awardTime'; break;
      case '学生获奖': dateField = 'awardTime'; break;
      case '继续教育材料': dateField = 'obtainTime'; break;
      case '著作': dateField = 'publishDate'; break;
      case '新闻报道': dateField = 'reportTime'; break;
      case '档案资料': dateField = 'obtainTime'; break;
      case '其他': dateField = 'obtainTime'; break;
      case '横向课题': dateField = 'startTime'; break;
      case '纵向课题': dateField = 'startTime'; break;
    }

    currentData = currentData.filter(item => {
      if (!item[dateField]) return false;
      const itemDate = new Date(item[dateField])
      return itemDate >= startDate && itemDate <= endDate
    })
  }

  // 如果选择了本人排名，进行过滤
  if (selectedPerson.value) {
    // 根据不同类型选择对应的排名字段
    let rankField = 'authorRank'
    if (selectedType.value === '横向课题' || selectedType.value === '纵向课题') {
      rankField = 'rank'
    }

    if (selectedPerson.value === '第1名' || selectedPerson.value === '前1名' || selectedPerson.value === '第一名') {
      currentData = currentData.filter(item => item[rankField] === '1' || item[rankField] === 1)
    } else if (selectedPerson.value === '前2名') {
      currentData = currentData.filter(item => {
        const rank = parseInt(item[rankField])
        return !isNaN(rank) && rank <= 2
      })
    } else if (selectedPerson.value === '前3名') {
      currentData = currentData.filter(item => {
        const rank = parseInt(item[rankField])
        return !isNaN(rank) && rank <= 3
      })
    } else if (selectedPerson.value === '第二名') {
      currentData = currentData.filter(item => item[rankField] === '2' || item[rankField] === 2)
    } else if (selectedPerson.value === '第三名') {
      currentData = currentData.filter(item => item[rankField] === '3' || item[rankField] === 3)
    } else if (selectedPerson.value === '第四名') {
      currentData = currentData.filter(item => item[rankField] === '4' || item[rankField] === 4)
    } else if (selectedPerson.value === '第五名') {
      currentData = currentData.filter(item => item[rankField] === '5' || item[rankField] === 5)
    }
    // '全部排名'不需要过滤
  }

  return currentData.map(item => {
    const filteredItem = {}
    getVisibleHeaders(selectedType.value).forEach(header => {
      const prop = getPropertyName(selectedType.value, header)
      filteredItem[prop] = item[prop]
    })
    return filteredItem
  })
})

// 获取当前类型的数据
const getCurrentData = () => {
  switch (selectedType.value) {
    case '论文': return papersData.value
    case '专利': return patentData.value
    case '软件著作权': return copyrightData.value
    case '个人获奖': return personalAwardData.value
    case '学生获奖': return studentAwardData.value
    case '继续教育材料': return cemData.value
    case '著作': return publicationData.value
    case '新闻报道': return reportData.value
    case '档案资料': return certificationData.value
    case '其他': return otherData.value
    case '横向课题': return horizontalData.value
    case '纵向课题': return longitudinalData.value
    default: return []
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString()
}

// 导出到Excel
const exportToExcel = () => {
  if (!selectedType.value) return

  const headers = getVisibleHeaders(selectedType.value)
  const data = filteredData.value.map((item, index) => {
    const row = { '序号': index + 1 }
    headers.forEach(header => {
      const prop = getPropertyName(selectedType.value, header)
      row[header] = formatCellValue(item[prop], header)
    })
    return row
  })

  const ws = XLSX.utils.json_to_sheet(data)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, selectedType.value)
  XLSX.writeFile(wb, `${selectedType.value}汇总表.xlsx`)
}

// 导出到Word
const exportToWord = async () => {
  if (!selectedType.value) return

  const doc = new Document({
    sections: [{
      properties: {},
      children: [
        new Paragraph({
          text: `${selectedType.value}汇总表`,
          heading: 'Heading1'
        }),
        createTable()
      ]
    }]
  })

  const buffer = await Packer.toBlob(doc)
  saveAs(buffer, `${selectedType.value}汇总表.docx`)
}

// 创建Word文档表格
const createTable = () => {
  const headers = ['序号', ...getVisibleHeaders(selectedType.value)]
  const rows = [
    new TableRow({
      children: headers.map(header =>
          new TableCell({
            children: [new Paragraph({ text: header })],
            width: {
              size: 100 / headers.length,
              type: WidthType.PERCENTAGE,
            },
          })
      ),
    }),
    ...filteredData.value.map((item, index) =>
        new TableRow({
          children: [
            new TableCell({
              children: [new Paragraph({ text: (index + 1).toString() })],
            }),
            ...getVisibleHeaders(selectedType.value).map(header => {
              const prop = getPropertyName(selectedType.value, header)
              // 确保正确获取和格式化个人排名数据
              let value = item[prop]
              if (header === '本人排名') {
                value = value || '-' // 如果排名为空则显示'-'
              }
              return new TableCell({
                children: [new Paragraph({ text: value ? value.toString() : '-' })],
              })
            }),
          ],
        })
    ),
  ]

  return new Table({
    rows,
    width: {
      size: 100,
      type: WidthType.PERCENTAGE,
    },
    borders: {
      top: { style: BorderStyle.SINGLE, size: 1 },
      bottom: { style: BorderStyle.SINGLE, size: 1 },
      left: { style: BorderStyle.SINGLE, size: 1 },
      right: { style: BorderStyle.SINGLE, size: 1 },
      insideHorizontal: { style: BorderStyle.SINGLE, size: 1 },
      insideVertical: { style: BorderStyle.SINGLE, size: 1 },
    },
  })
}

// 调用API获取数据
const fetchPersonalCount = async () => {
  try {
    const response = await getUserPersonalCount()
    if (response.code === 1) {
      const data = response.data
      counts.value = [
        data.paperCount,
        data.longitudinalProjectCount,
        data.patentCount,
        data.copyrightCount,
        data.awardPersonalCount,
        data.awardStudentCount,
        data.materialCount,
        data.publicationCount,
        data.horizontalProjectCount,
        data.reportCount,
        data.certificateinfoCount,
        data.otherCount
      ]
    } else {
      console.error('获取数据失败:', response.msg)
    }
  } catch (error) {
    console.error('API 请求错误:', error)
  }
}

// 获取专利数据
const fetchPatentData = async () => {
  try {
    const response = await getPatentsBySummary()
    if (response.code === 1) {
      patentData.value = response.data
    } else {
      console.error('获取专利数据失败:', response.msg)
    }
  } catch (error) {
    console.error('获取专利数据错误:', error)
  }
}

// 获取软件著作权数据
const fetchCopyrightData = async () => {
  try {
    const response = await getCopyRightsBySummary()
    if (response.code === 1) {
      copyrightData.value = response.data
    } else {
      console.error('获取软件著作权数据失败:', response.msg)
    }
  } catch (error) {
    console.error('获取软件著作权数据错误:', error)
  }
}

// 获取个人获奖数据
const fetchPersonalAwardData = async () => {
  try {
    const response = await getPersonalAwardsBySummary()
    if (response.code === 1) {
      personalAwardData.value = response.data
    } else {
      console.error('获取个人获奖数据失败:', response.msg)
    }
  } catch (error) {
    console.error('获取个人获奖数据错误:', error)
  }
}

// 获取学生获奖数据
const fetchStudentAwardData = async () => {
  try {
    const response = await getStudentAwardsBySummary()
    if (response.code === 1) {
      studentAwardData.value = response.data
    } else {
      console.error('获取学生获奖数据失败:', response.msg)
    }
  } catch (error) {
    console.error('获取学生获奖数据错误:', error)
  }
}

// 获取继续教育材料数据
const fetchCemData = async () => {
  try {
    const response = await getcemBySummary()
    if (response.code === 1) {
      cemData.value = response.data
    } else {
      console.error('获取继续教育材料数据失败:', response.msg)
    }
  } catch (error) {
    console.error('获取继续教育材料数据错误:', error)
  }
}

// 获取著作数据
const fetchPublicationData = async () => {
  try {
    const response = await getcemPublicationSummary()
    if (response.code === 1) {
      publicationData.value = response.data
    } else {
      console.error('获取著作数据失败:', response.msg)
    }
  } catch (error) {
    console.error('获取著作数据错误:', error)
  }
}

// 获取新闻报道数据
const fetchReportData = async () => {
  try {
    const response = await getreportBySummary()
    if (response.code === 1) {
      reportData.value = response.data
    } else {
      console.error('获取新闻报道数据失败:', response.msg)
    }
  } catch (error) {
    console.error('获取新闻报道数据错误:', error)
  }
}

// 获取档案资料数据
const fetchCertificationData = async () => {
  try {
    const response = await getcertificationBySummary()
    if (response.code === 1) {
      certificationData.value = response.data
    } else {
      console.error('获取档案资料数据失败:', response.msg)
    }
  } catch (error) {
    console.error('获取档案资料数据错误:', error)
  }
}

// 获取其他数据
const fetchOtherData = async () => {
  try {
    const response = await getotherBySummary()
    if (response.code === 1) {
      otherData.value = response.data
    } else {
      console.error('获取其他数据失败:', response.msg)
    }
  } catch (error) {
    console.error('获取其他数据错误:', error)
  }
}

// 获取横向课题数据
const fetchHorizontalData = async () => {
  try {
    const response = await gethorizontalBySummary()
    if (response.code === 1) {
      horizontalData.value = response.data
    } else {
      console.error('获取横向课题数据失败:', response.msg)
    }
  } catch (error) {
    console.error('获取横向课题数据错误:', error)
  }
}

// 获取纵向课题数据
const fetchLongitudinalData = async () => {
  try {
    const response = await getlongitudinalBySummary()
    if (response.code === 1) {
      longitudinalData.value = response.data
    } else {
      console.error('获取纵向课题数据失败:', response.msg)
    }
  } catch (error) {
    console.error('获取纵向课题数据错误:', error)
  }
}

// 获取论文数据
const fetchPapersData = async () => {
  try {
    const response = await getpapersBySummary()
    if (response.code === 1) {
      papersData.value = response.data
    } else {
      console.error('获取论文数据失败:', response.msg)
    }
  } catch (error) {
    console.error('获取论文数据错误:', error)
  }
}

// 更新selectedType的值并获取相应数据
const updateSelectedType = (header) => {
  selectedType.value = header
  switch (header) {
    case '论文':
      fetchPapersData()
      break
    case '专利':
      fetchPatentData()
      break
    case '软件著作权':
      fetchCopyrightData()
      break
    case '个人获奖':
      fetchPersonalAwardData()
      break
    case '学生获奖':
      fetchStudentAwardData()
      break
    case '继续教育材料':
      fetchCemData()
      break
    case '著作':
      fetchPublicationData()
      break
    case '新闻报道':
      fetchReportData()
      break
    case '档案资料':
      fetchCertificationData()
      break
    case '其他':
      fetchOtherData()
      break
    case '横向课题':
      fetchHorizontalData()
      break
    case '纵向课题':
      fetchLongitudinalData()
      break
  }
}

// 删除行
const deleteRow = (index) => {
  ElMessageBox.confirm('确定要删除这一行吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        const currentData = getCurrentData();
        currentData.splice(index, 1);
        ElMessage({
          type: 'success',
          message: '行删除成功!',
        });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
        });
      });
}

// 确保DOM加载完成后再执行样式修复
const fixHeaderStyles = () => {
  nextTick(() => {
    // 强制重新计算样式
    const headerElement = document.querySelector('.header');
    if (headerElement) {
      // 触发重绘
      headerElement.style.display = 'flex';
      headerElement.style.alignItems = 'center';
    }
  });
};

// 在组件挂载时调用
onMounted(() => {
  fetchPersonalCount();
  // 修复标题样式问题
  fixHeaderStyles();
})
</script>

<style scoped>
.container {
  padding: 0 24px;
  background: #fff;
  min-height: 100vh;
  width: 80%;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  margin: 2vh auto 0;
}

.header {
  display: flex;
  align-items: center;
  flex-wrap: nowrap; /* 防止换行 */
  margin-top: 20px; /* 增加顶部间距 */
}

.title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin: 0; /* 重置默认margin */
  padding: 0; /* 重置默认padding */
  margin-right: 10px;
  line-height: 1.2; /* 调整行高 */
}

.subtitle {
  font-size: 14px;
  color: #999;
  margin: 0; /* 重置默认margin */
  padding: 0; /* 重置默认padding */
  align-self: center; /* 确保垂直居中 */
  line-height: 1.2; /* 调整行高 */
}

.select-wrapper {
  position: relative;
  display: inline-block;
}

.select-wrapper select {
  appearance: none;
  padding: 8px 30px 8px 12px;
  font-size: 14px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  background: #fff;
  color: #333;
  min-width: 160px;
  cursor: pointer;
}

.select-wrapper select option[disabled] {
  color: #999;
  background: #f5f5f5;
  cursor: default;
}

.select-arrow {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid #666;
  pointer-events: none;
}

.table-container {
  width: 100%;
  overflow-x: auto;
}

.summary-table,
.detail-table {
  width: 100%;
  border-collapse: collapse;
  text-align: center;
}

.summary-table th,
.summary-table td,
.detail-table th,
.detail-table td {
  border: 1px solid #e0e0e0;
  padding: 12px;
  font-size: 14px;
}

.summary-table th {
  background: #f5f5f5;
  color: #666;
  font-weight: normal;
}

.summary-table td {
  color: #333;
}

.highlight {
  color: #00b96b !important;
}

.detail-section {
  margin-top: 40px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 20px;
}

.filters {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  align-items: center;
  flex-wrap: wrap; /* 允许在小屏幕上换行 */
}

.generate-btn {
  padding: 12px 24px;
  font-size: 16px;
  color: #333;
  background: #f5f5f5;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.generate-btn:hover {
  background: #e8e8e8;
}

.detail-table th {
  background: #f5f5f5;
  color: #666;
  font-weight: normal;
  min-width: 100px;
}

.detail-table td {
  height: 40px;
  color: #333;
}

.row-header {
  background: #f5f5f5;
  color: #666;
  font-weight: normal;
}

.divider {
  width: calc(100% + 48px);
  margin-left: -24px;
  border: none;
  height: 1px;
  background-color: #e0e0e0;
  margin-bottom: 20px;
  margin-top: 10px; /* 增加顶部间距 */
}

.summary-table th:hover,
.summary-table td:hover {
  background-color: #e0e0e0;
}

.export-btn {
  padding: 12px 24px;
  font-size: 16px;
  color: #fff;
  background: #1890ff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.export-btn:hover {
  background: #40a9ff;
}

.export-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}

.header-cell {
  position: relative;
  padding-right: 30px !important;
}

.delete-btn {
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s;
}

.header-cell:hover .delete-btn {
  opacity: 1;
}

.delete-icon {
  width: 16px;
  height: 16px;
  color: #ff4d4f;
}

.delete-btn:hover .delete-icon {
  color: #ff7875;
}

.delete-btn:active {
  transform: translateY(-50%) scale(0.95);
}

.delete-row-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0.5;
  transition: opacity 0.2s;
  margin: 0 auto; /* Added for proper alignment */
}

.delete-row-btn:hover {
  opacity: 1;
}

.delete-row-btn .delete-icon {
  width: 16px;
  height: 16px;
  color: #ff4d4f;
}

.delete-row-btn:hover .delete-icon {
  color: #ff7875;
}

.delete-row-btn:active {
  transform: scale(0.95);
}

/* 添加日期范围选择器样式 */
.date-range-picker {
  display: flex;
  align-items: center;
}

.date-label {
  font-size: 14px;
  color: #666;
  margin-right: 8px;
}

/* 确保Element Plus日期选择器样式正确 */
:deep(.el-date-editor.el-input__wrapper) {
  width: 260px;
}

:deep(.el-range-separator) {
  padding: 0 4px;
}

/* 添加响应式样式 */
@media (max-width: 768px) {
  .container {
    width: 95%;
    padding: 0 12px;
  }

  .filters {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }

  .date-range-picker {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
